package com.siriuscloud.holidayreservation.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siriuscloud.holidayreservation.domain.Holiday;
import com.siriuscloud.holidayreservation.domain.vo.HolidayVo;
import com.siriuscloud.holidayreservation.mapper.HolidayMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class HolidayService {

    @Resource
    private HolidayMapper holidayMapper;

    final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    final QueryWrapper<Holiday> queryWrapper = new QueryWrapper<>();

    public List<Holiday> getAllHoliday(Date startDate, Date endDate, Integer type) {
        QueryWrapper<Holiday> queryWrapper = new QueryWrapper<>();
        if (startDate != null) {
            queryWrapper.ge("date", startDate.getTime());
        }

        if (endDate != null) {
            queryWrapper.le("date", endDate.getTime());
        }

        if (null != type) {
            queryWrapper.eq("type", type);
        }
        return holidayMapper.selectList(queryWrapper);
    }

    public Boolean create(HolidayVo holidayVo) {
        Date date = null;
        try {
            date = dateFormat.parse(holidayVo.getDate());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (null == date) return false;

        queryWrapper.eq("date", date);
        if(holidayMapper.selectCount(queryWrapper) > 0) {
            return false;
        }

        Holiday holiday = new Holiday();
        holiday.setId(holidayVo.getId());
        holiday.setDate(String.valueOf(date.getTime()));
        holiday.setType(holidayVo.getType());
        if(holidayMapper.insert(holiday) == 0) {
            return false;
        }
        return holidayMapper
                .insertByDepartment(String.valueOf(date.getTime())) > 0;
    }

    public Boolean update(Holiday holiday) {
        queryWrapper.eq("date", Long.parseLong(holiday.getDate()));
        Holiday holiday1 = new Holiday();
        holiday1.setType(holiday.getType());
        return holidayMapper.update(holiday1, queryWrapper) > 0;
    }
}
